<?php

include('../../include/functions.inc.php');
if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 's':
            stepA($db, $user);
            break;
        case 'invoice':
            stepB($db, $user);
            break;
        case 'pay':
            stepC($db, $user);
            break;
        case 'refresh':
            loadCareer($db);
            break;
        case 'aiu':
            findStudent($db, 'AIU_CODE=' . getParam('AIU_CODE'));
            break;
        case 'id':
            findStudent($db, 'ID=' . getParam('ID'));
            break;
        case 'stud':
            listStudents();
            break;
        case 'p':
            printInvoice($db);
            break;
    }
}

function listStudents() {
    header('Location: ../students/slistStudents.php');
}

function findStudent($db, $where) {
    $r = $db->query_select("cllg_student", $where);
    $datos = array();
    if (count($r) > 0) {
        $c = $r[0];
        $l = $db->query_select('cllg_account', "FK_STUDENT=" . $c['ID']);
        $ac = $l[0];
        if (count($ac) > 0) {
            $datos = array('NAME' => $c['FIRTS_NAME'] . ',' . $c['LAST_NAME'], 'ID' => $c['ID'],
                'AIU' => ($c['AIU_CODE'] != NULL) ? $ac['AIU_CODE'] : "", 'AC' => $ac['ID']);
        } else {
            $datos = array('ERROR' => 'NO TIENE CUENTA CORRIENTE EN ESTA ENTIDAD!');
        }
    } else {
        $datos = array('ERROR' => 'NO EXISTE NINGUN ESTUDIANTE CON ESE CODIGO!');
    }
    $_SESSION['pack'] = serialize($datos);
    header('Location: ../../include/transport.php');
}

function stepA($db, $user) {
    $student = getParam('ID');
    $rs = $db->query_select('cllg_account', 'FK_STUDENT=' . $student);
    $ac = $rs[0];

    $cbalance = $ac["CURR_BALANCE"];
    $cargos = json_decode(stripslashes(getParam('json')), TRUE);
    $total = 0;
    $penal = 0;
    $now = date("Y-m-d", strtotime(getParam("FECHAPAGO")));
    $pagos = array();
    $details = array();
    $memCargos = array();
    $memAbonos = array();

    $mora = 0;
    $moneda = 1;
    foreach ($cargos as $c) {
        $pbalance = $cbalance;
        $moneda = $c["MONEDA"];
        $fPago = NULL;
        $dataCargo = array(
            'TOTAL' => sqlValue($c["TOT"], 'double'),
            'TOTAL_PENDIENTE' => sqlValue(($c["TOT"] - $c["ABONO"]), 'double'),
            'ABONO' => sqlValue($c["ABONO"], 'double'));
        if ($c["ABONO"] == $c["TOT"]) { // si cancela por completo el cargo
            $fPago = sqlValue($now, 'date');
            $dataCargo['DATE_PAYED'] = $fPago;
        }

        //guardan los cargos a modificar
        $memCargos[] = array("key" => $c["ID"], "value" => $dataCargo);

        $abono = $c["ABONO"];
        $penal = $c["PENAL"];
        $cbalance+=$abono;
        $total+=$abono;
        $dataAbono = array("FK_ACCOUNT" => sqlValue($ac["ID"], 'int'),
            "CREATED" => sqlValue($now, 'date'),
            "CREATED_BY" => sqlValue($user->name, "text"),
            "DESCRIPTION" => sqlValue($c["DESCRIPTION"], 'text'),
            "TOTAL" => sqlValue($abono, 'float'),
            "CURR_BALANCE" => sqlValue($cbalance, "float"),
            "PREV_BALANCE" => sqlValue($pbalance, "float"),
            "PENALTY" => sqlValue($penal, "float"));

        $memAbonos[] = array("key" => $c["ID"], "value" => $dataAbono);
        $details[] = array("DESC" => $c["DESCRIPTION"], "MONTO" => $abono - $penal);

        if ($penal > 0) {
            $details[] = array("DESC" => "Pago Mora", "MONTO" => $penal);
            $mora = $mora + $penal;
        }
    }
    $datosCuenta = array("value" => array('CURR_BALANCE' => $cbalance, 'PREV_BALANCE' => $pbalance), "key" => $ac['ID']);

    $invoice = array();
    $invoice["factura"] = getNoFact($db, $user->entity);
    $invoice["cc"] = $datosCuenta;
    //obtiene el nit de la factura de campos dinamicos
    $r = getFieldValue($db, "cllg_student", $student, "NIT");
    $r = $r[0];
    $invoice["nit"] = $r["VALUE"];

    //obtiene la direccion de la factura de campos dinamicos
    $r = getFieldValue($db, "cllg_student", $student, "DIR_FACTURA");
    $r = $r[0];
    $invoice["dir"] = $r["VALUE"];

    //obtiene el nombre de la factura de campos dinamicos
    $r = getFieldValue($db, "cllg_student", $student, "NOMBRE_FACTURA");
    $r = $r[0];
    $invoice["nombre"] = $r["VALUE"];

    $invoice["nombreEst"] = getParam("NAME");
    $invoice["total"] = $total;
    $invoice["moneda"] = $moneda;
    $invoice["iva"] = $total * 0.12;
    $invoice["idstudent"] = $student;
    $invoice["mora"] = $mora;
    $invoice["detalle"] = $details;

    $invoice["listCargos"] = $memCargos;
    $invoice["listAbonos"] = $memAbonos;

    $_SESSION["invoice"] = serialize($invoice);

    header('Location: invoice.php');
}

/*
 * Guarda la informacion general de factur y llama los metodos
 * para modificar cargos, cuenta corriente y abonos.
 */

function stepB($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $next = getNextFactura($db, $invoice["factura"]["SERIE"], $user->entity);
    $next++;
    $invoice["factura"]["NUMERO"] = $next;
    $inicio = $invoice["factura"]["INICIO"];
    if ($next < $inicio) {
        $next = $inicio;
    }
    $sinMora = 0;
    $sinMora = $invoice["mora"];
    $totalDolares = 0;
    $tasaCambio = getParam("TASA");
    if ($invoice["moneda"] == 2) {//SI FUE PAGO EN DOLARES
        $totalDolares = getParam("TOTAL");
        $sinMora *= $tasaCambio;
    }
    $invoice["tasa"] = $tasaCambio;
    //guardando factura en memoria
    $factura = array(
        "NUMERO" => $next,
        "SERIE" => sqlValue($invoice["factura"]["SERIE"], "text"),
        "FK_STUDENT" => $invoice["idstudent"],
        "FECHA" => sqlValue(getParam("FECHAFAC"), "date"),
        "TOTAL" => sqlValue(getParam("TOTAL_REAL"), "double"),
        "NOMBRE" => sqlValue(getParam("NAME"), "text"),
        "DIRECCION" => sqlValue(getParam("ADDRESS"), "text"),
        "NIT" => sqlValue(getParam("NIT"), "text"),
        "IVA" => sqlValue(getParam("IVA"), "double"),
        "SUBTOTAL" => sqlValue(getParam("TOTAL_REAL") - getParam("IVA"), "double"),
        "FK_ENTITY" => $user->entity,
        "NO_BOLETA" => sqlValue($invoice["boleta"], "text"),
        "MORA" => sqlValue($sinMora, "double"),
        "STATUS" => sqlValue(getParam("STATUS"), "int"),
        "TASA_CAMBIO" => $tasaCambio,
        "DOLARES" => $totalDolares);


    //guardando detalle de factura
    $det = $invoice["detalle"];
    $detalle = array();
    foreach ($det as $d) {
        $montoQ = 0;
        $montoD = 0;
        if ($invoice["moneda"] == 2) {
            $montoQ = $d["MONTO"] * $invoice["tasa"];
            $montoD = $d["MONTO"];
        } else {
            $montoQ = $d["MONTO"];
        }
        $line = array("DESCRIPCION" => sqlValue($d["DESC"], "text"),
            "CANTIDAD" => 1, "SUBTOTAL" => $montoQ, "FK_FACTURA" => 0,
            "SUBTOTAL_DOLARES" => $montoD);
        $detalle[] = $line;
    }

    $invoice["total"] = getParam("TOTAL_REAL");
    $invoice["ready"] = array("head" => $factura, "detail" => $detalle);

    //guarda la factura para la impresion
    $_SESSION["invoice"] = serialize($invoice);

    if ($factura["STATUS"] == 2) {
        saveAllData($db, $user);
    } else {
        header('Location: wayspay.php?urlData=data.php');
    }
}

function stepC($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $factura = $invoice["ready"];
    $head = $factura["head"];

    $head["EFECTIVO"] = sqlValue(getParam("EFECTIVO"), "double");
    $head["TARJETA"] = sqlValue(getParam("TARJETA"), "double");
    $head["DEPOSITO"] = sqlValue(getParam("DEPOSITO"), "double");
    $head["NO_BOLETA"] = sqlValue(getParam("NO_BOLETA"), "text");
    $head["CHEQUE"] = sqlValue(getParam("CHEQUE"), "double");

    if (doubleval(getParam("CHEQUE") > 0)) {
        $invoice["chk"] = array("NUMERO" => getParam("NOCHEKE"),
            "BANCO" => getParam("BANCO"),
            "MONTO" => getParam("CHEQUE"),
            "FECHACOBRO" => getParam("FECHACOBRO"),
            "CONCEPTO" => getParam("CONCEPTO"));
    }

    $factura["head"] = $head;
    $invoice["ready"] = $factura;
    $_SESSION["invoice"] = serialize($invoice);

    saveAllData($db, $user);
}

/*
 * Modifica los cargos pagados, registra abonos y luego alista la
 * informacion para que se guarde la relacion de los cargos,abonos y factura.
 */

function saveCargoAbono($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $memCargos = $invoice["listCargos"];
    $memAbonos = $invoice["listAbonos"];
    $pagos = array();

    //actualiza los cargos afectados
    foreach ($memCargos as $cargo) {
        $intCiclo = 0;
        $strQuery ="SELECT  cllg_student_assign.FK_CYCLE
                    FROM    cllg_cargo,
                            cllg_student_assign
                    WHERE   cllg_cargo.ID = {$cargo["key"]}
                    AND     cllg_cargo.FK_STUDENT_ASSIGN = cllg_student_assign.ID";
        $db->query($strQuery);
        while ($arrFila = $db->fetch_assoc()) {
            $intCiclo = $arrFila['FK_CYCLE'];
        }
        $db->free_result($db->query_id);
        if ($intCiclo > 0) {
            $strQuery = "UPDATE cllg_college_cycle SET MONEY_IN = MONEY_IN + {$cargo['value']['ABONO']} WHERE CODE = {$intCiclo} AND FK_ENTITY = " . $user->entity;
            $db->query($strQuery);
        }
        unset($cargo['value']['ABONO']);
        $db->query_update('cllg_cargo', $cargo["value"], "ID=" . $cargo["key"]);
    }
    //registra los abonos realizados
    foreach ($memAbonos as $abono) {
        $db->query_insert('cllg_abono', $abono["value"]);
        $idAbono = getLastAbono($db);
        $monto = $abono["value"]["TOTAL"];
        $pagos[] = array("CARGO" => $abono["key"], "ABONO" => $idAbono, "MONTO" => $monto);
    }

    //actualiza cuenta corriente
    $cta = $invoice["cc"];
    $db->query_update('cllg_account', $cta["value"], 'ID=' . $cta["key"]);

    //actualiza datos del ciclo
    /* $cy = getCycle($db, $user);
      $totalIn = $cy["MONEY_IN"] + $invoice["total"];
      $db->query_update("cllg_college_cycle", array("MONEY_IN" => $totalIn), "CODE=" . $user->cycle . " AND FK_ENTITY=" . $user->entity); */

    $invoice["pagos"] = $pagos;
    $_SESSION["invoice"] = serialize($invoice);
}

/*
 * Guarda la informacion de cargos,abonos y factura
 */

function saveRelation($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);
    $idFactura = $invoice["id"];
    $pagos = $invoice["pagos"];
    foreach ($pagos as $pago) {
        $db->query_insert("cllg_mov_cargo", array("FK_CARGO" => $pago["CARGO"],
            "FK_FACTURA" => $idFactura,
            "FK_ABONO" => $pago["ABONO"],
            "MONTO" => $pago["MONTO"],
            "CREATED" => sqlValue(date("y-m-d"), "date"),
            "CREATED_BY" => sqlValue($user->name, "text")));
    }
}

/*
 * Guarda la informacion de medio de pago con cheque
 */

function saveCheque($db, $valCk) {
    $cheque = array("NUMERO" => sqlValue($valCk["NUMERO"], "text"),
        "FECHA" => sqlValue(date("y-m-d"), "date"),
        "MONTO" => sqlValue($valCk["MONTO"], "double"),
        "BANCO" => sqlValue($valCk["BANCO"], "text"),
        "FK_FACURA" => sqlValue($valCk["FACTURA"], "int"),
        "FECHA_COBRO" => sqlValue($valCk["FECHACOBRO"], "date"));
    $db->query_insert("cllg_cheque", $cheque);
}

/*
 * Genera toda la informacion que se va imprimir
 * en la pagina de format.php que contiene el formato
 */

function printInvoice($db) {
    $invoice = unserialize($_SESSION["invoice"]);
    $serie = $invoice["factura"]["SERIE"];
    $numero = $invoice["factura"]["NUMERO"];
    $nombreEs = getParam("NOMBRE2");
    $carrera = $invoice["CARRERA"];
    header("Location: ../invoices/format.php?SERIE=$serie&NUMERO=$numero&NAME=$nombreEs&CARRERA=$carrera");
}

function getNoFact($db, $entity) {
    $f = $db->query_select("cllg_factura_serie", "STATUS=1 AND FK_ENTITY=" . $entity);
    if (count($f) > 0) {
        return $f[0];
    }
    return null;
}

function getNextFactura($db, $serie, $entity) {
    $f = $db->queryToArray("select max(NUMERO) No FROM cllg_factura WHERE FK_ENTITY=" . $entity .
            " AND SERIE=" . sqlValue($serie, "text"));
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 0;
    }
}

function getNextIDFactura($db) {
    $f = $db->queryToArray("select max(ID) as No FROM cllg_factura");
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 1;
    }
}

function getLastAbono($db) {
    $f = $db->queryToArray("select max(ID) as No FROM cllg_abono");
    if (count($f) > 0 && !isEmpty($f[0]["No"])) {
        return $f[0]["No"];
    } else {
        return 1;
    }
}

/*
 * Guarda todos los datos de cargos pagados
 * registra los movimientos y el historial
 * de la facturacion.
 */

function saveAllData($db, $user) {
    $invoice = unserialize($_SESSION["invoice"]);

    //persiste la informacion de la factura
    $head = $invoice["ready"]["head"];
    $db->query_insert("cllg_factura", $head);

    $fk = getNextIDFactura($db);
    $invoice["id"] = $fk;
    $details = $invoice["ready"]["detail"];
    $factura = $invoice["ready"]["head"];
    foreach ($details as $det) {
        $det["FK_FACTURA"] = $fk;
        $db->query_insert("cllg_factura_detalle", $det);
    }
    $_SESSION["invoice"] = serialize($invoice);

    //modifica informacion de cargos y abonos
    saveCargoAbono($db, $user);

    //guarda la informacion de relacion cargo,abono y factura
    saveRelation($db, $user);

    //guarda los datos del cheque
    $cheque = $invoice["chk"];
    if ($cheque != null) {
        $cheque["FACTURA"] = $fk;
        saveCheque($db, $cheque);
    }

    //recopila informacion de la carrera que aparecera en la factura
    $assigns = listStudentAssigns($db, $invoice["idstudent"], $user);
    $assigns = $assigns[0];
    $carrera = getCareerName($assigns["FK_CAREER"], $db);
    $invoice["CARRERA"] = $carrera;

    if ($head["STATUS"] == 1) { //si la factura fue pagada!
        $res = array("R" => 1,
            "FACTURA" => $invoice["factura"]["SERIE"] . "-" . $invoice["factura"]["NUMERO"],
            "CARRERA" => $carrera);

        $_SESSION['pack'] = serialize($res);
        header('Location: ../../include/transport.php');
    } else { //si se dejo pendiente de pago entonces se imprime la factura
        printInvoice($db);
    }
}

?>
